package com.suyeer.common;

import com.suyeer.basic.util.ConstUtil;
import com.suyeer.basic.util.HttpResUtil;
import com.suyeer.basic.util.LogUtil;
import org.apache.http.HttpStatus;
import org.apache.log4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.regex.Pattern;

import static org.apache.commons.codec.CharEncoding.UTF_8;

/**
 * @author jun 2018/12/7
 */
public class AuthFilter implements Filter {

    private final HashSet<String> PASS_URI_SET = new HashSet<>();

    /**
     * User: jun
     * Date: 2017/8/7
     * Desc: 实现拦截器
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        try {
            if (isPass(hrc.getReqURI())) {
                chain.doFilter(request, response);
            } else if (hrc.isNotLogin() || hrc.isNotPermission()) {
                sendError(hrc);
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            LogUtil.error(e);
            response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            MDC.clear();
        }
    }

    /**
     * User: jun
     * Date: 2017/8/7
     * Desc: 返回错误页面或错误提示
     */
    private void sendError(HttpResContent<String> hrc) throws Exception {
        HttpStatusEnum codeEnum = hrc.getHttpStatus();
        LogUtil.error(codeEnum.getDes());
        if (hrc.getReqMethod().equalsIgnoreCase(ConstUtil.GET)) {
            if (codeEnum == HttpStatusEnum.UNAUTHORIZED) {
                hrc.getResponse().sendRedirect("/?backUrl=" + URLEncoder.encode(hrc.getReqQueryURI(), UTF_8));
            } else {
                hrc.getResponse().sendError(codeEnum.getCode(), codeEnum.getDes());
            }
        } else {
            hrc.fillData(codeEnum.getCode(), codeEnum.getDes(), null);
            HttpResUtil.writeResult(hrc);
        }
    }

    /**
     * User: jun
     * Date: 2017/8/7
     * Desc: 静态资源uri和免登陆uri返回true
     */
    private Boolean isPass(String uri) {
        Pattern p = Pattern.compile("^/.*\\.(txt|ico|js|css|jpg|png|swf|svg|map)$");
        return p.matcher(uri).matches() || PASS_URI_SET.contains(uri)
                || uri.startsWith("/test") || uri.startsWith("/tool")
                || uri.startsWith("/wx");
    }

    @Override
    public void destroy() {
        LogUtil.info("系统下线...");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LogUtil.info("系统部署成功...");
    }
}